package com.dqv5.shorturl.config;

import com.dqv5.shorturl.service.MainService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

/**
 * 启动后自动执行
 */
@Component
@Slf4j
public class AppReadyListener implements ApplicationListener<ApplicationReadyEvent> {

    @Value("${shorturl.reinit:false}")
    private Boolean reinit;
    @Autowired
    private DataSource dataSource;
    @Autowired
    private MainService mainService;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        log.info("--------------初始化程序开始--------------");
        //1.表结构检查
        initStructure();
        //2.执行加注释的SQL脚本
        initSql();
        //3.初始化数据
        if (reinit) {
            initData();
        }
        log.info("--------------初始化程序结束--------------");

    }


    private void initStructure() {
        try {
            log.info("【初始化表表结构】开始...");
            log.info("【初始化表表结构】完成");
        } catch (Exception e) {
            log.error("【初始化表结构】错误", e);
        }
    }

    private void initSql() {
        try {
            log.info("【初始化表注释SQL】开始...");
            log.info("【初始化表注释SQL】完成");
        } catch (Exception e) {
            log.error("【初始化表注释SQL】错误", e);
        }
    }

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private void initData() {
        log.info("【初始化系统数据】开始....");
        log.info("【初始化系统数据】完成");
    }
}

